#include "msgQueue.h"
#include "bank.h"
#include "tools.h"

//通信消息
ClientToServe ctos;
ServeToClient stoc;

//消息队列ID
int stocMsgId = 0;
int ctosMsgId = 0;

void transfer(void)
{
	char srcPath[PATH_LEN] = {},destPath[PATH_LEN] = {};

	sprintf(srcPath,"%s%s",ACC_PATH,ctos.acc.bank);
	sprintf(destPath,"%s%s",ACC_PATH,ctos.acc.IdCard);

	//判断银行卡号是否正确
	if(0 != access(destPath,F_OK))
	{
		sprintf(stoc.info,"N:目标卡号不存在，请检查!");
		return;
	}

	int srcFd = open(srcPath,O_RDWR);
	int destFd = open(destPath,O_RDWR);
	if(0 > srcFd || 0 > destFd)
	{
		error("open");
		sprintf(stoc.info,"N:服务器正在升级，转账失败");
		return;
	}

	Acc srcAcc = {},destAcc = {};
	read(srcFd,&srcAcc,sizeof(Acc));
	read(destFd,&destAcc,sizeof(Acc));

	if(srcAcc.balance < ctos.acc.balance)
	{
		sprintf(stoc.info,"N:余额不足，转账失败!当前余额为：%g",srcAcc.balance);
		return;
	}

	srcAcc.balance -= ctos.acc.balance;
	destAcc.balance += ctos.acc.balance;

	lseek(srcFd,0,SEEK_SET);
	lseek(destFd,0,SEEK_SET);
	write(srcFd,&srcAcc,sizeof(Acc));
	write(destFd,&destAcc,sizeof(Acc));
	close(srcFd);
	close(destFd);

	sprintf(stoc.info,"Y:转账成功，当前余额为:%g",srcAcc.balance);
}

int main()
{
	//获取两个消息队列
	stocMsgId = getMsg(STOC_KEY);
	ctosMsgId = getMsg(CTOS_KEY);

	while(true)
	{
		ctos.type = M_TRANSFER;
		receiveMsg(ctosMsgId,&ctos,sizeof(ctos));

		transfer();

		stoc.type = ctos.pid;
		sendMsg(stocMsgId,&stoc,sizeof(stoc));
	}
}
